package org.opsli.modulars.business.iot.handler;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import org.json.JSONObject;
import org.opsli.api.wrapper.business.fileManage.FileManageModel;
import org.opsli.api.wrapper.business.valveDeviceHis.ValveDeviceHisModel;
import org.opsli.api.wrapper.business.valveDeviceNow.ValveDeviceNowModel;
import org.opsli.api.wrapper.business.valveDeviceNowHis.ValveDeviceNowHisModel;
import org.opsli.api.wrapper.czData.CzDataModel;
import org.opsli.common.utils.CheckStrength;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.czData.service.ICzDataService;
import org.opsli.modulars.business.equipment.entity.*;
import org.opsli.modulars.business.equipment.service.IEquipmentService;
import org.opsli.modulars.business.fileManage.service.IFileManageService;
import org.opsli.modulars.business.iot.protocol.*;
import org.opsli.modulars.business.valveDevice.entity.ValveDevice;
import org.opsli.modulars.business.valveDevice.service.IValveDeviceService;
import org.opsli.modulars.business.valveDeviceHis.service.IValveDeviceHisService;
import org.opsli.modulars.business.valveDeviceNow.service.IValveDeviceNowService;
import org.opsli.modulars.business.valveDeviceNowHis.service.IValveDeviceNowHisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author sst
 * @version V1.0
 * @Package com.lysoft.monitoring.iot.handler
 * @date 2019-08-22 14:24
 * 在线设备数据采集业务处理
 */
@Component
@ChannelHandler.Sharable
public class BusinessHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IValveDeviceService valveDeviceService;
    @Autowired
    private IValveDeviceNowService valveDeviceNowService;
    @Autowired
    private IValveDeviceHisService valveDeviceHisService;
    @Autowired
    private IFileManageService fileManageService;
    @Autowired
    private IValveDeviceNowHisService nowHisService;

    @Autowired
    private ICzDataService czDataService;
    @Autowired
    private IEquipmentService equipmentService;

    private static Logger log = LoggerFactory.getLogger(BusinessHandler.class);

    private Logger sjlog =  LoggerFactory.getLogger("sj");


    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);

    //    @Autowired
//    ISendMessageService sendMessageService;
    //每分钟设备发送一次数据往数据库，通过netty接收数据后存到redis缓存中，redis中包含两部分数据，一种是存放的每分钟设备数据的集合，一种放的是
    //最新的实时数据，每五分钟往redis取一次数据，存入数据库每五分钟表中，每小时往redis取一次数据，存入每小时表中
    @Override
    @Transactional(readOnly = false)
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg.toString());
        String data=msg.toString();
        Channel channel=ctx.channel();
        String key=SyncChannelUtil.getkey(channel);
        System.out.println("key="+key);
        if(ZkUtils.isBlank(key)){
            return;
        }
        recordLog(key,data);
        //前半部分
        String key1=key.substring(0,key.length()-1);
        //后半部分
        String key2=key.substring(key.length()-1,key.length());
        if(key2.equals("1")){
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //获取设备编号,mac地址
            byte[] bytes=ConvertCode.hexString2Bytes(data);
            String devid=data.substring(6,18);
           /* for(int i=3;i<=8;i++){
                devid=devid+BCDToStr(bytes[i]);
            }*/
            System.out.println("设备编号="+devid);
            if(devid.equals("002022047005")){
                sendTime(ctx,devid,key);
            }else {
                ValveDevice valveDevice = valveDeviceService.getDevice(devid);
                if (valveDevice == null) {
                    SyncChannelUtil.removeChannel(key);
                    channel.close();
                    return;
                } else {
                    //发送读报警字,电池电压,版本号请求
                    sendBYD(ctx, devid, key);
                }
            }
        }else if(key2.equals("2")){
            if(!data.substring(4,6).equals("0C")||data.length()!=34){
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            /*00 03 06 00 48 03 59 00 25 DD 67*/
            //获取报警字,电池电压,版本号
            byte[] bytes=ConvertCode.hexString2Bytes(data);
            DevAlarm alarm=BitUtil.getAlarm(data.substring(6,10));
            String voltage1=BCDToStr(bytes[5]);
            String voltage2=BCDToStr(bytes[6]);
            BigDecimal a1=new BigDecimal("100");
            BigDecimal a2=new BigDecimal(voltage1);
            BigDecimal a3=new BigDecimal(voltage2);
            BigDecimal a4=a3.divide(a1);
            //电压
            double d=(a2.add(a4)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            if(d==0){
                redisTemplate.opsForValue().set(key1+"type","485");
            }else{
                redisTemplate.opsForValue().set(key1+"type","fmj");
            }
            //版本号
            String version=data.substring(14,18);
            ValveDeviceNowModel nowModel=valveDeviceNowService.getOne(key1);
            Integer nd=covert(data.substring(20,22));
            //温度
            String ll=data.substring(22,26);
            BigDecimal b1=new BigDecimal(covert(ll));
            BigDecimal b2=new BigDecimal("10");
            String tem="";
            if(ll.startsWith("F")){
                BigDecimal b3=new BigDecimal(covert("FFFF"));
                b1=b3.subtract(b1);
                tem="-"+b1.divide(b2).toString();
            }else{
                tem=b1.divide(b2).toString();
            }
            String hum=covert(data.substring(26,30))+"";
            ValveDevice valveDevice=valveDeviceService.getDevice(key1);
            if(valveDevice.getDevid().equals("41005")){
                hum="99";
            }
            if(nowModel!=null){
                //做修改
                nowModel.setBit0(alarm.getBit0().toString());
                nowModel.setBit1(alarm.getBit1().toString());
                nowModel.setBit2(alarm.getBit2().toString());
                nowModel.setBit3(alarm.getBit3().toString());
                nowModel.setBit4(alarm.getBit4().toString());
                nowModel.setBit5(alarm.getBit5().toString());
                nowModel.setBit6(alarm.getBit6().toString());
                nowModel.setBit7(alarm.getBit7().toString());
                nowModel.setBit8(alarm.getBit8().toString());
                nowModel.setLastTime(ZkUtils.getDateStr());
                nowModel.setVoltage(String.valueOf(d));
                nowModel.setPotency(nd.toString());
                nowModel.setTemp(tem);
                nowModel.setHum(hum);
                nowModel.setDeviceVersion(version);
             /*  nowModel.setBit6("0");
               nowModel.setBit7("0");
               nowModel.setBit0("0");*/
             /*  if(key1.equals("002021092401")){
                   nowModel.setHum("48");
               }*/
                valveDeviceNowService.update(nowModel);
            }else{

                nowModel=new ValveDeviceNowModel();
                nowModel.setBit0(alarm.getBit0().toString());
                nowModel.setBit1(alarm.getBit1().toString());
                nowModel.setBit2(alarm.getBit2().toString());
                nowModel.setBit3(alarm.getBit3().toString());
                nowModel.setBit4(alarm.getBit4().toString());
                nowModel.setBit5(alarm.getBit5().toString());
                nowModel.setBit6(alarm.getBit6().toString());
                nowModel.setBit7(alarm.getBit7().toString());
                nowModel.setBit8(alarm.getBit8().toString());
                nowModel.setLastTime(ZkUtils.getDateStr());
                nowModel.setVoltage(String.valueOf(d));
                nowModel.setDevid(valveDevice.getDevid());
                nowModel.setDeviceId(key1);
                nowModel.setValveId(valveDevice.getValueId());
                nowModel.setPotency(nd.toString());
                nowModel.setHum(hum);
                nowModel.setTemp(tem);
                nowModel.setDeviceVersion(version);
             /*  nowModel.setBit6("0");
               nowModel.setBit7("0");
               nowModel.setBit0("0");*/
                valveDeviceNowService.insert(nowModel);
            }
            ValveDeviceNowHisModel nowHisModel=new ValveDeviceNowHisModel();
            nowHisModel.setBit0(alarm.getBit0().toString());
            nowHisModel.setBit1(alarm.getBit1().toString());
            nowHisModel.setBit2(alarm.getBit2().toString());
            nowHisModel.setBit3(alarm.getBit3().toString());
            nowHisModel.setBit4(alarm.getBit4().toString());
            nowHisModel.setBit5(alarm.getBit5().toString());
            nowHisModel.setBit6(alarm.getBit6().toString());
            nowHisModel.setBit7(alarm.getBit7().toString());
            nowHisModel.setBit8(alarm.getBit8().toString());
            nowHisModel.setLastTime(ZkUtils.getDateStr());
            nowHisModel.setVoltage(String.valueOf(d));
            nowHisModel.setDevid(valveDevice.getDevid());
            nowHisModel.setDeviceId(key1);
            nowHisModel.setValveId(valveDevice.getValueId());
            nowHisModel.setPotency(nd.toString());
            nowHisModel.setTemp(tem);
            nowHisModel.setHum(hum);
          /* nowHisModel.setBit6("0");
           nowHisModel.setBit7("0");
           nowHisModel.setBit0("0");
           if(key1.equals("002021092401")){
               nowHisModel.setHum("48");
           }*/
            nowHisService.insert(nowHisModel);
            //报警
            if(alarm.getBit1()==1||alarm.getBit2()==1||alarm.getBit3()==1){
                valveDeviceService.updateState(valveDevice.getDeviceId());
                ValveDeviceHisModel nowModel2 = new ValveDeviceHisModel();
                nowModel2.setBit0(alarm.getBit0().toString());
                nowModel2.setBit1(alarm.getBit1().toString());
                nowModel2.setBit2(alarm.getBit2().toString());
                nowModel2.setBit3(alarm.getBit3().toString());
                nowModel2.setBit4(alarm.getBit4().toString());
                nowModel2.setBit5(alarm.getBit5().toString());
                nowModel2.setBit6(alarm.getBit6().toString());
                nowModel2.setBit7(alarm.getBit7().toString());
                nowModel2.setBit8(alarm.getBit8().toString());
                nowModel2.setDevid(valveDevice.getDevid());
                nowModel2.setDeviceId(key1);
                nowModel2.setValveId(valveDevice.getValueId());
                /* String time = "20" + data.substring(6, 8) + "-" + data.substring(8, 10) + "-" + data.substring(10, 12) + " " + data.substring(12, 14) + ":" + data.substring(14, 16) + ":" + data.substring(16, 18);*/
                nowModel2.setLastTime(ZkUtils.getDateStr());
                nowModel2.setPotency(nd.toString());
                valveDeviceHisService.insert(nowModel2);
            }else{
                valveDeviceService.updateStateN(key1);
            }
            Integer newVersion=Integer.valueOf(version);
            Integer oldVersion=Integer.valueOf(valveDevice.getDeviceVersion());

            if(newVersion<oldVersion){
                sjlog.info("sjbegin,deviceId="+key1+",new="+newVersion+",old="+oldVersion);
                System.out.println("zkjs,new="+newVersion+",old="+oldVersion);
               /* String sjStr="002022047040,\n" +
                        "002022047041,\n" +
                        "002022047075,\n" +
                        "002022047093";*/
                String type=redisTemplate.opsForValue().get(key1+"type").toString();
                if(type.equals("485")){
                    String sjStr=newVersion+"";
                    if(sjStr.startsWith("3")||sjStr.startsWith("2")||sjStr.startsWith("4"))
                    {
                        redisTemplate.opsForValue().set(key1+"oldVersion",version,600, TimeUnit.SECONDS);
                        redisTemplate.opsForValue().set(key1+"newVersion",valveDevice.getDeviceVersion(),600, TimeUnit.SECONDS);
                        sendUploadBegin(ctx, key1, key);
                    }else{
                        sendTime(ctx,key1,key);
                    }
                }else  if(type.equals("fmj")){
                    String sjStr=newVersion+"";
                    if(sjStr.equals("21")) {
                        redisTemplate.opsForValue().set(key1+"oldVersion",version,600, TimeUnit.SECONDS);
                        redisTemplate.opsForValue().set(key1+"newVersion",valveDevice.getDeviceVersion(),600, TimeUnit.SECONDS);
                        sendUploadBegin(ctx, key1, key);
                    }else{
                        sendTime(ctx,key1,key);
                    }
                }
                /*if(sjStr.contains(key1))
                {
                    redisTemplate.opsForValue().set(key1+"oldVersion",version,600, TimeUnit.SECONDS);
                    redisTemplate.opsForValue().set(key1+"newVersion",valveDevice.getDeviceVersion(),600, TimeUnit.SECONDS);
                    sendUploadBegin(ctx, key1, key);
                }else{
                    sendTime(ctx,key1,key);
                }*/
            }else{
                if(key1.equals("002022087435")&&newVersion==402){
                    redisTemplate.opsForValue().set(key1+"oldVersion",version,600, TimeUnit.SECONDS);
                    redisTemplate.opsForValue().set(key1+"newVersion",valveDevice.getDeviceVersion(),600, TimeUnit.SECONDS);
                    sendUploadBegin(ctx, key1, key);
                }else {
                    sendTime(ctx, key1, key);
                }
            }

            /*sendTime(ctx,key1,key);*/

        }else if(key2.equals("3")){
            if(!data.substring(2,4).equals("10")||data.length()!=16){
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            System.out.println("校时"+key1);
            //校时完成
            if(key1.equals("002022047005")){
                System.out.println("场站设备校时完成,开始发送读数据请求");
                sendCz(ctx, key1, key);
            }else {
                sendHis(ctx, key1, key);
            }
        }else if(key2.equals("4")){
            if(!data.substring(4,6).equals("0A")||data.length()!=30){
                String readstr="00030000002045C3";
                sendMac1(ctx,key1,key,readstr);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //获取报警字,电池电压,版本号
            byte[] bytes=ConvertCode.hexString2Bytes(data);
            if(bytes[1]==0x03) {
                ValveDevice valveDevice = valveDeviceService.getDevice(key1);
                DevAlarm alarm = BitUtil.getAlarm(data.substring(22, 26));
                ValveDeviceHisModel nowModel = new ValveDeviceHisModel();
                nowModel.setBit0(alarm.getBit0().toString());
                nowModel.setBit1(alarm.getBit1().toString());
                nowModel.setBit2(alarm.getBit2().toString());
                nowModel.setBit3(alarm.getBit3().toString());
                nowModel.setBit4(alarm.getBit4().toString());
                nowModel.setBit5(alarm.getBit5().toString());
                nowModel.setBit6(alarm.getBit6().toString());
                nowModel.setBit7(alarm.getBit7().toString());
                nowModel.setBit8(alarm.getBit8().toString());
                nowModel.setDevid(valveDevice.getDevid());
                nowModel.setDeviceId(key1);
                nowModel.setValveId(valveDevice.getValueId());
                String time = "20" + data.substring(6, 8) + "-" + data.substring(8, 10) + "-" + data.substring(10, 12) + " " + data.substring(12, 14) + ":" + data.substring(14, 16) + ":" + data.substring(16, 18);
                nowModel.setLastTime(time);
                Integer nd=covert(BCDToStr(bytes[10]));
                nowModel.setPotency(nd.toString());
                valveDeviceHisService.insert(nowModel);
                //报警
                if(alarm.getBit1()==1||alarm.getBit2()==1||alarm.getBit3()==1||alarm.getBit6()==1){
                    valveDeviceService.updateState(key1);
                }
                String value = "";
                if (valveDevice.getHis().equals("0")) {
                    value = "77";
                } else {
                    Integer loc = Integer.valueOf(valveDevice.getHis()) + 5;
                    value = String.valueOf(loc);
                }
                valveDeviceService.updateOne(value, key1);
                sendHis(ctx, key1, key);
            }else{
                //读取第一部分数据
                String readstr="00030000002045C3";
                sendMac1(ctx,key1,key,readstr);

            }
        }else if(key2.equals("7")){
            if(!data.contains("B6")){
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            FileManageModel fileManageModel=new FileManageModel();
            String type=redisTemplate.opsForValue().get(key1+"type").toString();
            if(type.equals("485")){
               /* if(key1.equals("202206291400")||key1.equals("002022067327")||key1.equals("002022067322")){
                    fileManageModel=fileManageService.get("108");
                }else{
                    fileManageModel=fileManageService.get("107");
                }*/
                if(key1.equals("002022047030")||key1.equals("002022087435")){
                    fileManageModel=fileManageService.get("110");
                }else if(key1.equals("002022087002")){
                    fileManageModel=fileManageService.get("112");
                }else{
                    fileManageModel=fileManageService.get("108");
                }


            }else if(type.equals("fmj")){
               /* if(key1.equals("002022047030")){
                    fileManageModel=fileManageService.get("110");
                }else if(key1.equals("002022087002")){
                    fileManageModel=fileManageService.get("111");
                }else{
                    fileManageModel=fileManageService.get("109");
                }*/
                fileManageModel=fileManageService.get("109");
            }
            String path=fileManageModel.getDocpath()+fileManageModel.getFilepath();
            String s=HexUtil.readFile(path);
            redisTemplate.opsForValue().set(key1+"version",s,600, TimeUnit.SECONDS);
            //获取开始升级结果
            String result=data.substring(6,8);
            if(result.equals("B6")){
                redisTemplate.opsForValue().set(key1+"sj","0",600, TimeUnit.SECONDS);
                sendUpload(ctx,key1,key);
            }
        }else if(key2.equals("10")){
            if(!data.contains("C9")){
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //获取开始升级结果
            String result=data.substring(6,8);
            if(result.equals("C9")){
                sendTime(ctx,key1,key);
            }
        }else if(key2.equals("8")){
            if(!data.contains("A5")){
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //获取开始升级结果
            String result=data.substring(6,8);
            if(result.equals("A5")){
                sendUpload(ctx,key1,key);
            }
        }else if(key2.equals("9")){
            if(!data.contains("A5")){
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //获取开始升级结果
            String result=data.substring(6,8);
            if(result.equals("A5")){
                sendUploadEnd(ctx,key1,key);
                UpgradeLog upgradeLog=new UpgradeLog();
                upgradeLog.setDeviceId(key1);
                String oldVersion=redisTemplate.opsForValue().get(key1+"oldVersion").toString();
                String newVersion=redisTemplate.opsForValue().get(key1+"newVersion").toString();
                upgradeLog.setOldVersion(oldVersion);
                upgradeLog.setNewVersion(newVersion);
                upgradeLog.setUpgradeTime(new Date());
                try {
                    equipmentService.insertUpgradeLog(upgradeLog);
                }catch (Exception e){

                }
            }
        }else if(key2.equals("z")){
            //解析场站数据
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            System.out.println("场站数据"+data);
            try {
                CzDataModel czsj=CzsjUtil.getdata(data);
                System.out.println("场站实体数据"+JSON.toJSONString(czsj));
                czDataService.insert(czsj);
            }catch (Exception e){

            }
            SyncChannelUtil.addChannel(key,ctx.channel());
        }else if(key2.equals("a")){
            if(!data.substring(2,4).equals("03")){
                sjlog.info("读取4G数据第一部分异常,devid="+key1);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            Map map=new HashMap();
            map= ReadZb.getZb1(data);
            sjlog.info("读取4G数据第一部分解析,devid="+key1+",json="+JSON.toJSONString(map));
            String type=redisTemplate.opsForValue().get(key1+"type").toString();
            if(type.equals("485")){
                GatewayMonitorData monitorData=new GatewayMonitorData();
                monitorData.setMac(map.get("mac").toString());
                monitorData.setIp(map.get("ip").toString());
                monitorData.setPort(map.get("port").toString());
                monitorData.setApn(map.get("apn").toString());
                monitorData.setCjmin(map.get("cjmin").toString());
                monitorData.setScmin(map.get("scmin").toString());
                monitorData.setDeviceId(key1);
                monitorData.setCreateTime(ZkUtils.getDateStr());
                equipmentService.insertGatewayMonitorData(monitorData);
                GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                if(now==null){
                    now=new GatewayMonitorDataNow();
                    now.setMac(map.get("mac").toString());
                    now.setIp(map.get("ip").toString());
                    now.setPort(map.get("port").toString());
                    now.setApn(map.get("apn").toString());
                    now.setCjmin(map.get("cjmin").toString());
                    now.setScmin(map.get("scmin").toString());
                    now.setDeviceId(key1);
                    now.setCreateTime(ZkUtils.getDateStr());
                    equipmentService.insertGatewayMonitorDataNow(now);
                }else{
                    now.setMac(map.get("mac").toString());
                    now.setIp(map.get("ip").toString());
                    now.setPort(map.get("port").toString());
                    now.setApn(map.get("apn").toString());
                    now.setCjmin(map.get("cjmin").toString());
                    now.setScmin(map.get("scmin").toString());
                    now.setDeviceId(key1);
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                }


            }else{
                ValveMonitorData monitorData=new ValveMonitorData();
                monitorData.setMac(map.get("mac").toString());
                monitorData.setIp(map.get("ip").toString());
                monitorData.setPort(map.get("port").toString());
                monitorData.setApn(map.get("apn").toString());
                monitorData.setCjmin(map.get("cjmin").toString());
                monitorData.setScmin(map.get("scmin").toString());
                monitorData.setDeviceId(key1);
                monitorData.setCreateTime(new Date());
                equipmentService.insertValveMonitorData(monitorData);
                ValveMonitorDataNow now=equipmentService.getValveMonitorDataNow(key1);
                if(now==null){
                    now=new ValveMonitorDataNow();
                    now.setMac(map.get("mac").toString());
                    now.setIp(map.get("ip").toString());
                    now.setPort(map.get("port").toString());
                    now.setApn(map.get("apn").toString());
                    now.setCjmin(map.get("cjmin").toString());
                    now.setScmin(map.get("scmin").toString());
                    now.setDeviceId(key1);
                    now.setCreateTime(new Date());
                    equipmentService.insertValveMonitorDataNow(now);
                }else{
                    now.setMac(map.get("mac").toString());
                    now.setIp(map.get("ip").toString());
                    now.setPort(map.get("port").toString());
                    now.setApn(map.get("apn").toString());
                    now.setCjmin(map.get("cjmin").toString());
                    now.setScmin(map.get("scmin").toString());
                    now.setDeviceId(key1);
                    now.setUpdateTime(new Date());
                    equipmentService.updateValveMonitorDataNow(now);
                }
            }
            //读取第一部分数据
            String readstr="00030020002845CF";
            sendMac2(ctx,key1,key,readstr);
        }else if(key2.equals("b")){
            if(!data.substring(2,4).equals("03")){
                sjlog.info("读取4G数据第二部分异常,devid="+key1);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            Map map=new HashMap();
            map= ReadZb.getZb22(data);
            sjlog.info("读取4G数据第二部分解析,devid="+key1+",json="+JSON.toJSONString(map));
            String type=redisTemplate.opsForValue().get(key1+"type").toString();
            if(type.equals("485")){
                GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                monitorData.setDevcetime(map.get("time").toString());
                monitorData.setDy(map.get("lelad3").toString());
                monitorData.setVersion(map.get("version").toString());
                monitorData.setUpdateTime(ZkUtils.getDateStr());
                equipmentService.updateGatewayMonitorData(monitorData);

                GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                now.setDevcetime(map.get("time").toString());
                now.setDy(map.get("lelad3").toString());
                now.setVersion(map.get("version").toString());
                now.setUpdateTime(ZkUtils.getDateStr());
                equipmentService.updateGatewayMonitorDataNow(now);

            }else{
                ValveMonitorData monitorData=equipmentService.getValveMonitorData(key1);
                monitorData.setBbit0(map.get("bbit0").toString());
                monitorData.setBbit1(map.get("bbit1").toString());
                monitorData.setBbit2(map.get("bbit2").toString());
                monitorData.setBbit3(map.get("bbit3").toString());
                monitorData.setBbit4(map.get("bbit4").toString());
                monitorData.setBbit5(map.get("bbit5").toString());
                monitorData.setPhone1(map.get("phone1").toString());
                monitorData.setPhone2(map.get("phone2").toString());
                monitorData.setPhone3(map.get("phone3").toString());
                monitorData.setPhone4(map.get("phone4").toString());
                monitorData.setPhone5(map.get("phone5").toString());
                monitorData.setDevcetime(map.get("time").toString());
                monitorData.setLelad1(map.get("lelad1").toString());
                monitorData.setLelad2(map.get("lelad2").toString());
                monitorData.setLelad3(map.get("lelad3").toString());
                monitorData.setBit0(map.get("bit0").toString());
                monitorData.setBit1(map.get("bit1").toString());
                monitorData.setBit2(map.get("bit2").toString());
                monitorData.setBit3(map.get("bit3").toString());
                monitorData.setBit4(map.get("bit4").toString());
                monitorData.setBit5(map.get("bit5").toString());
                monitorData.setBit6(map.get("bit6").toString());
                monitorData.setBit7(map.get("bit7").toString());
                monitorData.setBit8(map.get("bit8").toString());
                monitorData.setDy(map.get("dy").toString());
                monitorData.setVersion(map.get("version").toString());
                equipmentService.updateValveMonitorData(monitorData);

                ValveMonitorDataNow now=equipmentService.getValveMonitorDataNow(key1);
                now.setBbit0(map.get("bbit0").toString());
                now.setBbit1(map.get("bbit1").toString());
                now.setBbit2(map.get("bbit2").toString());
                now.setBbit3(map.get("bbit3").toString());
                now.setBbit4(map.get("bbit4").toString());
                now.setBbit5(map.get("bbit5").toString());
                now.setPhone1(map.get("phone1").toString());
                now.setPhone2(map.get("phone2").toString());
                now.setPhone3(map.get("phone3").toString());
                now.setPhone4(map.get("phone4").toString());
                now.setPhone5(map.get("phone5").toString());
                now.setDevcetime(map.get("time").toString());
                now.setLelad1(map.get("lelad1").toString());
                now.setLelad2(map.get("lelad2").toString());
                now.setLelad3(map.get("lelad3").toString());
                now.setBit0(map.get("bit0").toString());
                now.setBit1(map.get("bit1").toString());
                now.setBit2(map.get("bit2").toString());
                now.setBit3(map.get("bit3").toString());
                now.setBit4(map.get("bit4").toString());
                now.setBit5(map.get("bit5").toString());
                now.setBit6(map.get("bit6").toString());
                now.setBit7(map.get("bit7").toString());
                now.setBit8(map.get("bit8").toString());
                now.setDy(map.get("dy").toString());
                now.setVersion(map.get("version").toString());
                equipmentService.updateValveMonitorDataNow(now);




            }
            //读取传感器数据
            String readstr="0005000000164DD5";
            sendCgq(ctx,key1,key,readstr);

        }else if(key2.equals("c")){
            if(!data.substring(2,4).equals("05")){
                sjlog.info("读取传感器数据异常,devid="+key1);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            Map map=new HashMap();
            map= ReadCgq.getData(data);
            sjlog.info("读取传感器数据,devid="+key1+",json="+JSON.toJSONString(map));
            //判断是不是485设备
            String type=redisTemplate.opsForValue().get(key1+"type").toString();
            System.out.println("zzcytype="+type);
            if(type.equals("485")){
                GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                monitorData.setData2(map.get("data2").toString());
                monitorData.setData3(map.get("data3").toString());
                monitorData.setData4(map.get("data4").toString());
                monitorData.setData5(map.get("data5").toString());
                monitorData.setData6(map.get("data6").toString());
                monitorData.setData7(map.get("data7").toString());
                monitorData.setData8(map.get("data8").toString());
                monitorData.setData9(map.get("data9").toString());
                monitorData.setData10(map.get("data10").toString());
                monitorData.setData11(map.get("data11").toString());
                monitorData.setData12(map.get("data12").toString());
                monitorData.setData13(map.get("data13").toString());
                monitorData.setData14(map.get("data14").toString());
                monitorData.setData15(map.get("data15").toString());
                monitorData.setData16(map.get("data16").toString());
                monitorData.setData17(map.get("data17").toString());
                monitorData.setData18(map.get("data18").toString());
                monitorData.setData19(map.get("data19").toString());
                monitorData.setData20(map.get("data20").toString());
                monitorData.setData21(map.get("data21").toString());
                monitorData.setUpdateTime(ZkUtils.getDateStr());
                equipmentService.updateGatewayMonitorData(monitorData);

                GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                now.setData2(map.get("data2").toString());
                now.setData3(map.get("data3").toString());
                now.setData4(map.get("data4").toString());
                now.setData5(map.get("data5").toString());
                now.setData6(map.get("data6").toString());
                now.setData7(map.get("data7").toString());
                now.setData8(map.get("data8").toString());
                now.setData9(map.get("data9").toString());
                now.setData10(map.get("data10").toString());
                now.setData11(map.get("data11").toString());
                now.setData12(map.get("data12").toString());
                now.setData13(map.get("data13").toString());
                now.setData14(map.get("data14").toString());
                now.setData15(map.get("data15").toString());
                now.setData16(map.get("data16").toString());
                now.setData17(map.get("data17").toString());
                now.setData18(map.get("data18").toString());
                now.setData19(map.get("data19").toString());
                now.setData20(map.get("data20").toString());
                now.setData21(map.get("data21").toString());
                now.setUpdateTime(ZkUtils.getDateStr());
                equipmentService.updateGatewayMonitorDataNow(now);
                //读取流量计通道数
                String data3=map.get("data3").toString();
                //读取AI通道数
                String data5=map.get("data5").toString();
                redisTemplate.opsForValue().set(key1+"data3",data3,300, TimeUnit.SECONDS);
                redisTemplate.opsForValue().set(key1+"data5",data5,300, TimeUnit.SECONDS);
                redisTemplate.opsForValue().set(key1+"sort3","2",300, TimeUnit.SECONDS);
                redisTemplate.opsForValue().set(key1+"sort5","1",300, TimeUnit.SECONDS);
                //读取AI压变进口出口异常
                String readstr="0005001000024C1F";
                sendData10(ctx,key1,key,readstr);
            }else{
                ValveMonitorData monitorData=equipmentService.getValveMonitorData(key1);
                monitorData.setData2(map.get("data2").toString());
                monitorData.setData3(map.get("data3").toString());
                monitorData.setData4(map.get("data4").toString());
                monitorData.setData5(map.get("data5").toString());
                monitorData.setData6(map.get("data6").toString());
                monitorData.setData7(map.get("data7").toString());
                monitorData.setData8(map.get("data8").toString());
                monitorData.setData9(map.get("data9").toString());
                monitorData.setData10(map.get("data10").toString());
                monitorData.setData11(map.get("data11").toString());
                monitorData.setData12(map.get("data12").toString());
                monitorData.setData13(map.get("data13").toString());
                monitorData.setData14(map.get("data14").toString());
                monitorData.setData15(map.get("data15").toString());
                monitorData.setData16(map.get("data16").toString());
                monitorData.setData17(map.get("data17").toString());
                monitorData.setData18(map.get("data18").toString());
                monitorData.setData19(map.get("data19").toString());
                monitorData.setData20(map.get("data20").toString());
                monitorData.setData21(map.get("data21").toString());
                monitorData.setData22(map.get("data22").toString());
                monitorData.setData23(map.get("data23").toString());
                monitorData.setUpdateTime(new Date());
                equipmentService.updateValveMonitorData(monitorData);

                ValveMonitorDataNow now=equipmentService.getValveMonitorDataNow(key1);
                now.setData2(map.get("data2").toString());
                now.setData3(map.get("data3").toString());
                now.setData4(map.get("data4").toString());
                now.setData5(map.get("data5").toString());
                now.setData6(map.get("data6").toString());
                now.setData7(map.get("data7").toString());
                now.setData8(map.get("data8").toString());
                now.setData9(map.get("data9").toString());
                now.setData10(map.get("data10").toString());
                now.setData11(map.get("data11").toString());
                now.setData12(map.get("data12").toString());
                now.setData13(map.get("data13").toString());
                now.setData14(map.get("data14").toString());
                now.setData15(map.get("data15").toString());
                now.setData16(map.get("data16").toString());
                now.setData17(map.get("data17").toString());
                now.setData18(map.get("data18").toString());
                now.setData19(map.get("data19").toString());
                now.setData20(map.get("data20").toString());
                now.setData21(map.get("data21").toString());
                now.setData22(map.get("data22").toString());
                now.setData23(map.get("data23").toString());
                now.setUpdateTime(new Date());
                equipmentService.updateValveMonitorDataNow(now);
                CmdValveConfigSend send=equipmentService.selectCmdValve(key1);
                sjlog.info("读取阀门井待发送配置,devid="+key1+"send="+JSON.toJSONString(send));
                if(send!=null){
                    redisTemplate.opsForValue().set(key1+"valvesend",String.valueOf(send.getId()),300, TimeUnit.SECONDS);
                    sendCmdValve(ctx,key1,key,send.getCmd());
                }
            }

        }else if(key2.equals("f")){
            if(!data.substring(2,4).equals("05")){
                sjlog.info("读取AI压变进口出口异常,devid="+key1);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            Map map=new HashMap();
            map= ReadCgq.getDatakk2(data,1);
            sjlog.info("读取AI压变进口出口解析,devid="+key1+",json="+JSON.toJSONString(map));
            GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
            monitorData.setData10(map.get("data").toString());
            monitorData.setUpdateTime(ZkUtils.getDateStr());
            equipmentService.updateGatewayMonitorData(monitorData);

            GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
            now.setData10(map.get("data").toString());
            now.setUpdateTime(ZkUtils.getDateStr());
            equipmentService.updateGatewayMonitorDataNow(now);
            //读取AI压变/差压/泄露通道数
            String readstr="000500120002EDDF";
            sendData11(ctx,key1,key,readstr);

        }else if(key2.equals("g")){
            if(!data.substring(2,4).equals("05")){
                sjlog.info("读取AI压变/差压/泄露通道数异常,devid="+key1);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            Map map=new HashMap();
            map= ReadCgq.getDatakk2(data,2);
            sjlog.info("读取AI压变/差压/泄露通道数解析,devid="+key1+",json="+JSON.toJSONString(map));
            GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
            monitorData.setData11(map.get("data").toString());
            monitorData.setUpdateTime(ZkUtils.getDateStr());
            equipmentService.updateGatewayMonitorData(monitorData);

            GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
            now.setData11(map.get("data").toString());
            now.setUpdateTime(ZkUtils.getDateStr());
            equipmentService.updateGatewayMonitorDataNow(now);
            String data3=redisTemplate.opsForValue().get(key1+"data3").toString();
            String data5=redisTemplate.opsForValue().get(key1+"data5").toString();
            //AI数
            Integer a1=Integer.valueOf(data5);
            //流量计通道数
            Integer a2=Integer.valueOf(data3);
            if(a1==0){
                if(a2>1){
                    //开始读二路流量计
                    String readstr="0005002C00028C13";
                    sendLlj(ctx,key1,key,readstr);
                }else{
                    Cmd485Send send=equipmentService.selectCmd485(key1);
                    if(send!=null){
                        redisTemplate.opsForValue().set(key1+"485send",String.valueOf(send.getId()),300, TimeUnit.SECONDS);
                        sendCmd485(ctx,key1,key,send.getCmd());
                    }
                }
            }else{
                //开始读AI1
                String readstr="0005002000024C10";
                sendAI(ctx,key1,key,readstr);
            }

        }else if(key2.equals("d")){
            if(!data.substring(2,4).equals("05")){
                sjlog.info("读取AI异常,devid="+key1);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            Map map=new HashMap();
            map= ReadCgq.getDatakk2(data,24);
            sjlog.info("读取AI解析,devid="+key1+",json="+JSON.toJSONString(map));
            String data5=redisTemplate.opsForValue().get(key1+"data5").toString();
            String sort5=redisTemplate.opsForValue().get(key1+"sort5").toString();
            Integer count=Integer.valueOf(data5);
            Integer sort=Integer.valueOf(sort5);
            String data3=redisTemplate.opsForValue().get(key1+"data3").toString();
            //流量计通道数
            Integer a2=Integer.valueOf(data3);
            if(sort==count){
                sjlog.info("读取AI完毕,devid="+key1);

                GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                if(sort==1) {
                    monitorData.setData18(map.get("data").toString());
                    monitorData.setData19(map.get("data2").toString());

                    now.setData18(map.get("data").toString());
                    now.setData19(map.get("data2").toString());
                }else if(sort==2) {
                    monitorData.setData24(map.get("data").toString());
                    monitorData.setData25(map.get("data2").toString());

                    now.setData24(map.get("data").toString());
                    now.setData25(map.get("data2").toString());
                }else if(sort==3) {
                    monitorData.setData26(map.get("data").toString());
                    monitorData.setData27(map.get("data2").toString());

                    now.setData26(map.get("data").toString());
                    now.setData27(map.get("data2").toString());

                }else if(sort==4) {
                    monitorData.setData28(map.get("data").toString());
                    monitorData.setData29(map.get("data2").toString());

                    now.setData28(map.get("data").toString());
                    now.setData29(map.get("data2").toString());
                }else if(sort==5) {
                    monitorData.setData30(map.get("data").toString());
                    monitorData.setData31(map.get("data2").toString());

                    now.setData30(map.get("data").toString());
                    now.setData31(map.get("data2").toString());
                }else if(sort==6) {
                    monitorData.setData32(map.get("data").toString());
                    monitorData.setData33(map.get("data2").toString());

                    now.setData32(map.get("data").toString());
                    now.setData33(map.get("data2").toString());
                }else if(sort==7) {
                    monitorData.setData34(map.get("data").toString());
                    monitorData.setData35(map.get("data2").toString());

                    now.setData34(map.get("data").toString());
                    now.setData35(map.get("data2").toString());
                }else if(sort==8) {
                    monitorData.setData36(map.get("data").toString());
                    monitorData.setData37(map.get("data2").toString());

                    now.setData36(map.get("data").toString());
                    now.setData37(map.get("data2").toString());

                }
                monitorData.setUpdateTime(ZkUtils.getDateStr());
                now.setUpdateTime(ZkUtils.getDateStr());
                equipmentService.updateGatewayMonitorData(monitorData);
                equipmentService.updateGatewayMonitorDataNow(now);


                //最后一包
                if(a2>1){
                    //开始读二路流量计
                    String readstr="0005002C00028C13";
                    sendLlj(ctx,key1,key,readstr);
                }else{
                    Cmd485Send send=equipmentService.selectCmd485(key1);
                    if(send!=null){
                        redisTemplate.opsForValue().set(key1+"485send",String.valueOf(send.getId()),300, TimeUnit.SECONDS);
                        sendCmd485(ctx,key1,key,send.getCmd());
                    }
                }
            }else{
                if(sort==1){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData18(map.get("data").toString());
                    monitorData.setData19(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData18(map.get("data").toString());
                    now.setData19(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第二路AI
                    redisTemplate.opsForValue().set(key1+"sort5","2",300, TimeUnit.SECONDS);
                    String readstr="000500380002CC17";
                    sendAI(ctx,key1,key,readstr);
                }else if(sort==2){
                    //开始发送第三路AI
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData24(map.get("data").toString());
                    monitorData.setData25(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData24(map.get("data").toString());
                    now.setData25(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    redisTemplate.opsForValue().set(key1+"sort5","3",300, TimeUnit.SECONDS);
                    String readstr="0005003C00028DD6";
                    sendAI(ctx,key1,key,readstr);
                }else if(sort==3){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData26(map.get("data").toString());
                    monitorData.setData27(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData26(map.get("data").toString());
                    now.setData27(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第四路AI
                    redisTemplate.opsForValue().set(key1+"sort5","4",300, TimeUnit.SECONDS);
                    String readstr="0005004000024C0E";
                    sendAI(ctx,key1,key,readstr);
                }else if(sort==4){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData28(map.get("data").toString());
                    monitorData.setData29(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData28(map.get("data").toString());
                    now.setData29(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第5路AI
                    redisTemplate.opsForValue().set(key1+"sort5","5",300, TimeUnit.SECONDS);
                    String readstr="0005004400020DCF";
                    sendAI(ctx,key1,key,readstr);
                }else if(sort==5){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData30(map.get("data").toString());
                    monitorData.setData31(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData30(map.get("data").toString());
                    now.setData31(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第6路AI
                    redisTemplate.opsForValue().set(key1+"sort5","6",300, TimeUnit.SECONDS);
                    String readstr="000500480002CDCC";
                    sendAI(ctx,key1,key,readstr);
                }else if(sort==6){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData32(map.get("data").toString());
                    monitorData.setData33(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData32(map.get("data").toString());
                    now.setData33(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第7路AI
                    redisTemplate.opsForValue().set(key1+"sort5","7",300, TimeUnit.SECONDS);
                    String readstr="0005004C00028C0D";
                    sendAI(ctx,key1,key,readstr);
                }else if(sort==7){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData34(map.get("data").toString());
                    monitorData.setData35(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData34(map.get("data").toString());
                    now.setData35(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第8路AI
                    redisTemplate.opsForValue().set(key1+"sort5","8",300, TimeUnit.SECONDS);
                    String readstr="0005005000024DCB";
                    sendAI(ctx,key1,key,readstr);
                }
            }
        }else if(key2.equals("e")){
            if(!data.substring(2,4).equals("05")){
                sjlog.info("读取485流量计异常,devid="+key1);
                return;
            }
            redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
            //解析数据
            Map map=new HashMap();
            map= ReadCgq.getDatakk2(data,24);
            sjlog.info("读取485流量计解析,devid="+key1+",json="+JSON.toJSONString(map));
            String data3=redisTemplate.opsForValue().get(key1+"data3").toString();
            String sort3=redisTemplate.opsForValue().get(key1+"sort3").toString();
            Integer count=Integer.valueOf(data3);
            Integer sort=Integer.valueOf(sort3);
            if(sort==count){

                GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                if(sort==2){
                    monitorData.setData38(map.get("data").toString());
                    monitorData.setData39(map.get("data2").toString());

                    now.setData38(map.get("data").toString());
                    now.setData39(map.get("data2").toString());
                }else if(sort==3){
                    monitorData.setData40(map.get("data").toString());
                    monitorData.setData41(map.get("data2").toString());

                    now.setData40(map.get("data").toString());
                    now.setData41(map.get("data2").toString());

                }else if(sort==4){
                    monitorData.setData42(map.get("data").toString());
                    monitorData.setData43(map.get("data2").toString());

                    now.setData42(map.get("data").toString());
                    now.setData43(map.get("data2").toString());
                }

                monitorData.setUpdateTime(ZkUtils.getDateStr());
                now.setUpdateTime(ZkUtils.getDateStr());
                equipmentService.updateGatewayMonitorData(monitorData);
                equipmentService.updateGatewayMonitorDataNow(now);

                //最后一包
                sjlog.info("读取485流量计完毕,devid="+key1);
                Cmd485Send send=equipmentService.selectCmd485(key1);
                if(send!=null){
                    redisTemplate.opsForValue().set(key1+"485send",String.valueOf(send.getId()),300, TimeUnit.SECONDS);
                    sendCmd485(ctx,key1,key,send.getCmd());
                }
            }else{
                if(sort==2){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData38(map.get("data").toString());
                    monitorData.setData39(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData38(map.get("data").toString());
                    now.setData39(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第三路
                    redisTemplate.opsForValue().set(key1+"sort3","3",300, TimeUnit.SECONDS);
                    String readstr="0005003000024DD5";
                    sendLlj(ctx,key1,key,readstr);
                }else if(sort==3){
                    GatewayMonitorData monitorData=equipmentService.getGatewayMonitorData(key1);
                    monitorData.setData40(map.get("data").toString());
                    monitorData.setData41(map.get("data2").toString());
                    monitorData.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorData(monitorData);

                    GatewayMonitorDataNow now=equipmentService.getGatewayMonitorDataNow(key1);
                    now.setData40(map.get("data").toString());
                    now.setData41(map.get("data2").toString());
                    now.setUpdateTime(ZkUtils.getDateStr());
                    equipmentService.updateGatewayMonitorDataNow(now);
                    //开始发送第4路流量计
                    redisTemplate.opsForValue().set(key1+"sort3","4",300, TimeUnit.SECONDS);
                    String readstr="0005003400020C14";
                    sendLlj(ctx,key1,key,readstr);
                }
            }
        } else if(key2.equals("h")){
            String id=redisTemplate.opsForValue().get(key1+"485send").toString();
            if(!data.substring(2,4).equals("06")&&!data.substring(2,4).equals("10")){
                sjlog.info("写485配置回复异常,devid="+key1+"id="+id);
                Cmd485Send cmd=new Cmd485Send();
                cmd.setId(Long.valueOf(id));
                cmd.setCmdState("3");
                equipmentService.updateCmd485(cmd);
                return;
            }else{
                sjlog.info("写485配置回复正常,devid="+key1+"id="+id);
                Cmd485Send cmd=new Cmd485Send();
                cmd.setId(Long.valueOf(id));
                cmd.setCmdState("2");
                equipmentService.updateCmd485(cmd);
                redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
                Cmd485Send send=equipmentService.selectCmd485(key1);
                if(send!=null){
                    redisTemplate.opsForValue().set(key1+"485send",String.valueOf(send.getId()),300, TimeUnit.SECONDS);
                    sendCmd485(ctx,key1,key,send.getCmd());
                }
            }
        }else if(key2.equals("i")){
            String id=redisTemplate.opsForValue().get(key1+"valvesend").toString();
            if(!data.substring(2,4).equals("06")&&!data.substring(2,4).equals("10")){
                sjlog.info("写阀门井配置回复异常,devid="+key1+"id="+id);
                CmdValveConfigSend cmd=new CmdValveConfigSend();
                cmd.setId(Integer.valueOf(id));
                cmd.setCmdstate("3");
                equipmentService.updateCmdValve(cmd);
                return;
            }else{
                sjlog.info("写阀门井配置回复正常,devid="+key1+"id="+id);
                CmdValveConfigSend cmd=new CmdValveConfigSend();
                cmd.setId(Integer.valueOf(id));
                cmd.setCmdstate("2");
                equipmentService.updateCmdValve(cmd);
                redisTemplate.opsForValue().set(key,"0",300, TimeUnit.SECONDS);
                CmdValveConfigSend send=equipmentService.selectCmdValve(key1);
                if(send!=null){
                    redisTemplate.opsForValue().set(key1+"valvesend",String.valueOf(send.getId()),300, TimeUnit.SECONDS);
                    sendCmdValve(ctx,key1,key,send.getCmd());
                }
            }
        }else{
            /*SyncChannelUtil.removeChannel(key);*/
        }

    }


    private void  recordLog(String key,String cmdStr){
        if(ZkUtils.isBlank(key)){
            return;
        }
        try {
            //前半部分
            String key1=key.substring(0,key.length()-1);
            //后半部分
            String key2=key.substring(key.length()-1,key.length());
            if(key2.equals("1")){
                ScheduleLog log = new ScheduleLog();
                log.setDeviceId(cmdStr.substring(6,18));
                log.setCmdType(1);
                log.setCmdContent(cmdStr);
                log.setCmdTime(new Date());
                equipmentService.insertScheduleLog(log);
            }else {
                ScheduleLog log = new ScheduleLog();
                log.setDeviceId(key1);
                log.setCmdType(1);
                log.setCmdContent(cmdStr);
                log.setCmdTime(new Date());
                equipmentService.insertScheduleLog(log);
            }
        }catch (Exception e){

        }

    }

    private void  recordSendLog(String devid,String cmdStr){
        if(ZkUtils.isBlank(devid)){
            return;
        }
        try {
            ScheduleLog log = new ScheduleLog();
            log.setDeviceId(devid);
            log.setCmdType(0);
            log.setCmdContent(cmdStr);
            log.setCmdTime(new Date());
            equipmentService.insertScheduleLog(log);
        }catch (Exception e){

        }

    }



    //发送升级开始
    private void sendUploadBegin(ChannelHandlerContext ctx,String devid,String oldkey){
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        writeToClient("68A0A136000000000016",ctx,"发送升级开始",devid);
        //存入缓存
        //3代表是第三步
        String key=devid+7;
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient("68A0A136000000000016",ctx,"发送升级开始2",devid);
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient("68A0A136000000000016",ctx,"发送升级开始3",devid);
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }


    //发送升级结束
    private void sendUploadEnd(ChannelHandlerContext ctx,String devid,String oldkey){
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        writeToClient("68A0A149000000000016",ctx,"发送升级结束",devid);
        sjlog.info("sjend,deviceId="+devid);
        //存入缓存
        //3代表是第三步
        String key=devid+10;
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient("68A0A149000000000016",ctx,"发送升级结束",devid);
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient("68A0A149000000000016",ctx,"发送升级结束",devid);
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }


    //发送升级
    private void sendUpload(ChannelHandlerContext ctx,String devid,String oldkey){
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String s=redisTemplate.opsForValue().get(devid+"version").toString();;
        String sort=redisTemplate.opsForValue().get(devid+"sj").toString();
        Integer i=Integer.valueOf(sort);
        redisTemplate.opsForValue().set(devid+"sj",String.valueOf((i+1)),600, TimeUnit.SECONDS);
        String[] result = HexUtil.splitStringByLength(s, 2048);
        Integer a=result[i].length()/32;
        a=a*16+(result[i].length()-(a*32))/2;
        String ss=HexUtil.change(a);
        if(ss.length()==1){
            ss="000"+ss;
        }
        if(ss.length()==2){
            ss="00"+ss;
        }
        if(ss.length()==3){
            ss="0"+ss;
        }
        Integer b=32+i*4;
        String zz=HexUtil.change(i+1);
        if(zz.length()==1){
            zz="0"+zz;
        }
        String hexstr="68"+HexUtil.change(b)+"0025"+zz+ss+result[i];
        byte[] bytes=ConvertCode.hexString2Bytes(result[i]);
        String z=ConvertCode.getCRC3(bytes);
        hexstr=hexstr+z+"16";
        writeToClient(hexstr,ctx,"发送升级1,sort="+i,devid);
        sjlog.info("sjing,deviceId="+devid+",sort="+i);
        //存入缓存
        //3代表是第三步
        String key="";
        if(i<result.length-1){
            key=devid+8;
        }else{
            key=devid+9;
        }
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        return;

    }


    //读取历史数据
    private void sendHis(ChannelHandlerContext ctx,String devid,String oldkey) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ValveDevice valveDevice=valveDeviceService.getDevice(devid);
        String his=valveDevice.getHis();
        Integer loc=0;
        if(his.equals("0")){
            loc=77;
        }else{
            loc=Integer.valueOf(his)+5;
        }

        //发送校时请求
        byte[] bytes=new byte[6];
        bytes[0]=0x00;
        bytes[1]=0x03;
        String zh=Integer.toHexString(loc);
        if(zh.length()==2){
            bytes[2]=0x00;
            bytes[3]=hexStringToBytes(zh);
        }else if(zh.length()==3) {
            bytes[2]=hexStringToBytes("0"+zh.substring(0,1));
            bytes[3]=hexStringToBytes(zh.substring(1,3));
        }else if(zh.length()==4) {
            bytes[2]=hexStringToBytes(zh.substring(0,2));
            bytes[3]=hexStringToBytes(zh.substring(2,4));
        }
        bytes[4]=0x00;
        bytes[5]=0x05;
        String s=ConvertCode.bytesToHexString(bytes);
        System.out.println(s);
        String ss=ConvertCode.getCRC3(bytes);

        /*ctx.write(msg);*/
        writeToClient(s+ss,ctx,"读历史数据",devid);
        //存入缓存
        //3代表是第三步
        String key=devid+4;
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
       /* fixedThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient(s+ss,ctx,"读历史数据2");
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient(s+ss,ctx,"读历史数据3");
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });*/
        return;
    }

    //读场站数据
    private void sendCz(ChannelHandlerContext ctx,String devid,String oldkey) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //发送校时请求
        byte[] bytes=new byte[4];
        bytes[0]=0x00;
        bytes[1]=0x08;
        bytes[2]=0x00;
        bytes[3]=0x34;
        String s=ConvertCode.bytesToHexString(bytes);
        System.out.println(s);
        String ss=ConvertCode.getCRC3(bytes);

        /*ctx.write(msg);*/
        writeToClient(s+ss,ctx,"读场站数据","");
        //存入缓存
        //3代表是第三步
        String key=devid+"z";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
        /*fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient(s+ss,ctx,"读场站数据2");
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient(s+ss,ctx,"读场站数据3");
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });*/
        return;
    }

    //发送校时请求
    private void sendTime(ChannelHandlerContext ctx,String devid,String oldkey) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //发送校时请求
        byte[] bytes=new byte[13];
        bytes[0]=0x00;
        bytes[1]=0x10;
        bytes[2]=0x00;
        bytes[3]=0x3F;
        bytes[4]=0x00;
        bytes[5]=0x03;
        bytes[6]=0x06;
        bytes[7]=hexStringToBytes(ZkUtils.getYY());;
        bytes[8]=hexStringToBytes(ZkUtils.getMM());
        bytes[9]=hexStringToBytes(ZkUtils.getDD());
        bytes[10]=hexStringToBytes(ZkUtils.getHH());
        bytes[11]=hexStringToBytes(ZkUtils.getMin());
        bytes[12]=hexStringToBytes(ZkUtils.getSS());
        String s=ConvertCode.bytesToHexString(bytes);
        System.out.println(s);
        String ss=ConvertCode.getCRC3(bytes);

        /*ctx.write(msg);*/
        writeToClient(s+ss,ctx,"校时",devid);
        //存入缓存
        //3代表是第三步
        String key=devid+3;
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
        fixedThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient(s+ss,ctx,"校时2",devid);
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient(s+ss,ctx,"校时3",devid);
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        return;
    }


    //发送读传感器数据
    private void sendCgq(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"读传感器数据",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"c";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
    }

    //发送读AI压变进口出口
    private void sendData10(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"读AI压变进口出口",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"f";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
        fixedThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient(readStr,ctx,"读AI压变进口出口2",devid);
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient(readStr,ctx,"读AI压变进口出口3",devid);
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    //发送485指令
    private void sendCmd485(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"发送485配置指令",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"h";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
    }

    //发送阀门井指令
    private void sendCmdValve(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        sjlog.info("开始发送阀门井配置,deviceId="+devid+",str="+readStr);
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"发送阀门井配置指令",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"i";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
    }

    //发送读AI压变/差压/泄露通道数
    private void sendData11(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"读AI压变/差压/泄露通道数",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"g";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
    }

    //发送读AI
    private void sendAI(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"读AI数据",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"d";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
    }

    //发送读流量计数据
    private void sendLlj(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"读流量计数据",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"e";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
    }

    //发送读4G数据第一部分
    private void sendMac1(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"读4G数据第一部分",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"a";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
    }

    //发送读4G数据第二部分
    private void sendMac2(ChannelHandlerContext ctx,String devid,String oldkey,String readStr) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       /* byte[] bytes=ConvertCode.hexString2Bytes(readStr);
        String ss=ConvertCode.getCRC3(bytes);*/
        writeToClient(readStr,ctx,"读4G数据第二部分",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+"b";
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());

    }

    //发送读报警字,电池电压,版本号请求
    private void sendBYD(ChannelHandlerContext ctx,String devid,String oldkey) {
        try {
            //睡眠1s
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //发送读报警字,电池电压,版本号请求
        byte[] bytes=new byte[6];
        bytes[0]=0x00;
        bytes[1]=0x03;
        bytes[2]=0x00;
        bytes[3]=0x45;
        bytes[4]=0x00;
        bytes[5]=0x06;
        String s=ConvertCode.bytesToHexString(bytes);
        System.out.println(s);
        String ss=ConvertCode.getCRC3(bytes);
        /*ctx.write(msg);*/
        writeToClient(s+ss,ctx,"读报警字,电池电压,版本号",devid);
        //存入缓存
        //2代表是第一步
        String key=devid+2;
        SyncChannelUtil.removeChannel(oldkey);
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
        fixedThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient(s+ss,ctx,"读报警字,电池电压,版本号2",devid);
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient(s+ss,ctx,"读报警字,电池电压,版本号3",devid);
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        return;
    }


    public  byte hexStringToBytes(String hexString) {

        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d[0];
    }

    public static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c); }



    /**

     * @功能: BCD码转为10进制串(阿拉伯数据)

     * @参数: BCD码

     * @结果: 10进制串

     */

    public static String BCDToStr(byte bcd) {

        int a = (bcd >> 4);
        int b = bcd & 0x0f;
        String s=String.valueOf(a) + String.valueOf(b);
        return s.replace("-","");
    }
    /**
     * 客户端下线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(date + " " + ctx.channel().remoteAddress() + " 客户端下线！");
    }
    @Override
    public void handlerAdded(ChannelHandlerContext ctx){
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(date + " " + ctx.channel().remoteAddress() + " 新的客户端加入！"+ctx.channel().id());
//        sendCheckCmd(ctx,"4101");

        /*  String msg="000300000003041A";*/
        //发送读取mac地址请求
        try {
            Thread.sleep(500);
        }catch (Exception e){

        }

        byte[] bytes=new byte[6];
        bytes[0]=0x00;
        bytes[1]=0x03;
        bytes[2]=0x00;
        bytes[3]=0x00;
        bytes[4]=0x00;
        bytes[5]=0x03;
        String s=ConvertCode.bytesToHexString(bytes);
        System.out.println(s);
        String ss=ConvertCode.getCRC3(bytes);
        /*ctx.write(msg);*/
        writeToClient(s+ss,ctx,"mac地址请求","");
        //存入缓存
        String str=ZkUtils.getRandomStr();
        //1代表是第一步
        String key=str+1;
        SyncChannelUtil.addChannel(key,ctx.channel());
        redisTemplate.opsForValue().set(key,"1",300, TimeUnit.SECONDS);
        fixedThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    String ll=redisTemplate.opsForValue().get(key).toString();
                    if(ll.equals("0")){
                        return;
                    }else{
                        //发送第二遍
                        writeToClient(s+ss,ctx,"mac地址请求2","");
                    }
                    fixedThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                String ll=redisTemplate.opsForValue().get(key).toString();
                                if(ll.equals("0")){
                                    return;
                                }else{
                                    //发送第三遍
                                    writeToClient(s+ss,ctx,"mac地址请求3","");
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });




    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(date + " " + ctx.channel().remoteAddress() + " 客户端断开连接！");
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        Channel channel = ctx.channel();
        if(channel.isActive())ctx.close();
    }


    /**
     * 公用回写数据到客户端的方法
     * @param channel
     * @param mark 用于打印/log的输出
     * <br>//channel.writeAndFlush(msg);//不行
     * <br>//channel.writeAndFlush(receiveStr.getBytes());//不行
     * <br>在netty里，进出的都是ByteBuf，楼主应确定服务端是否有对应的编码器，将字符串转化为ByteBuf
     */
    private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark,String devid) {
        try {
            ByteBuf bufff = Unpooled.buffer();//netty需要用ByteBuf传输
            bufff.writeBytes(ConvertCode.hexString2Bytes(receiveStr));//对接需要16进制
            channel.writeAndFlush(bufff).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    StringBuilder sb = new StringBuilder("");
                    if(!ZkUtils.isEmpty(mark)){
                        sb.append("【").append(mark).append("】");
                    }
                    if (future.isSuccess()) {
                        System.out.println(sb.toString()+"回写成功"+receiveStr);
                        log.info(sb.toString()+"回写成功"+receiveStr);
                    } else {
                        System.out.println(sb.toString()+"回写失败"+receiveStr);
                        log.error(sb.toString()+"回写失败"+receiveStr);
                    }
                }
            });
            if(ZkUtils.isNotBlank(devid)){
                //记录发送日志
                recordSendLog(devid,receiveStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用通用writeToClient()异常"+e.getMessage());
            log.error("调用通用writeToClient()异常：",e);
        }
    }





    //发送天气数据
    private int sendCalDataCmd(ChannelHandlerContext ctx,String devid) {
        try{
            Thread.sleep(3000);
        }catch(Exception e){
        }
        byte[] adderss = HexDump.hexStringToByteArray(devid);
        //1.通过设备号获取通道号
        //2.获取天气数据
        //3.发送校准数据
        /* ChanelRedis chanelRedis=(ChanelRedis) redisTemplate.opsForValue().get(devid);*/
       /* String is=(String) redisTemplate.opsForValue().get(devid);
        ChanelRedis chanelRedis= JSONArray.parseObject(is, ChanelRedis.class);*/
        TCPProtocol tcp = new TCPProtocol(adderss);
        tcp.setHeadLen((short)56);
        tcp.setAfn((byte)0xf1);
        tcp.setContentLength((byte)6);
        //pm2.5、pm10、CO(1位小数点)、SO2、NO2、O3
        return 1;
    }

    //发送校准指令
    private int sendCheckCmd(ChannelHandlerContext ctx,String devid) {
        try{
            Thread.sleep(3000);
        }catch(Exception e){
        }
        byte[] adderss = HexDump.hexStringToByteArray(devid);
        TCPProtocol tcp = new TCPProtocol(adderss);
        tcp.setHeadLen((short)21);
        tcp.setAfn((byte)0xf2);
        tcp.setContentLength((byte)1);
        tcp.setData(new byte[]{0x01});
        String currentTime = "";
        String[] arr = currentTime.split("-");
        byte[] dates =new byte[arr.length];
        for(int i=0;i<arr.length;i++){
            dates[i] = (byte)Integer.parseInt(arr[i]);
        }
        tcp.setDate(dates);
        ctx.writeAndFlush(tcp);
        return 1;
    }

    /**
     * @param: [content]
     * @return: int
     * @description: 十六进制转十进制
     */
    public static int covert(String content){
        int number=0;
        String [] HighLetter = {"A","B","C","D","E","F"};
        Map<String,Integer> map = new HashMap<>();
        for(int i = 0;i <= 9;i++){
            map.put(i+"",i);
        }
        for(int j= 10;j<HighLetter.length+10;j++){
            map.put(HighLetter[j-10],j);
        }
        String[]str = new String[content.length()];
        for(int i = 0; i < str.length; i++){
            str[i] = content.substring(i,i+1);
        }
        for(int i = 0; i < str.length; i++){
            number += map.get(str[i])*Math.pow(16,str.length-1-i);
        }
        return number;
    }

}
